<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" inline label-position="left" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="会员id" prop="id">
                  <el-input v-model="queryParams.id" placeholder="请输入会员id" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="会员账号" prop="username">
                  <el-input v-model="queryParams.username" placeholder="请输入会员账号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="真实姓名" prop="realname">
                  <el-input v-model="queryParams.realname" placeholder="请输入真实姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="推荐人id" prop="parentId">
                  <el-input v-model="queryParams.parentId" placeholder="请输入推荐人id" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="会员等级" prop="userLevel">
                  <el-input v-model="queryParams.userLevel" placeholder="请输入会员等级" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                    <el-option v-for="dict in stkj_number_status" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="排序字段" prop="sortField">
                  <el-select v-model="queryParams.sortField" placeholder="请选择排序字段" clearable>
                    <el-option v-for="dict in sktj_sort_field" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="排序方式" prop="ascOrDesc">
                  <el-select v-model="queryParams.ascOrDesc" placeholder="请选择排序方式" clearable>
                    <el-option v-for="dict in sktj_asc_desc" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24" :offset="20">
                <el-form-item label-width="0">
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>


    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['number:number:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['number:number:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="danger">
                删除
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-dropdown-item>
                  <el-dropdown-item icon="Delete" @click="handleDeleteAll()"> 全部删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="warning">
                导入
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Download" @click="importTemplate">下载模板</el-dropdown-item>
                  <el-dropdown-item icon="Top" @click="handleImport"> 导入数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="info">
                导出
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Download" @click="handleExport">全部导出</el-dropdown-item>
                  <el-dropdown-item icon="Download" :disabled="multiple" @click="handleExportByIds()">
                    选择导出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="numberList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="hasData('id') && true" label="会员id" align="center" prop="id" width="180" />
        <el-table-column v-if="hasData('username')" label="会员账号" align="center" prop="username" width="120"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('realname')" label="真实姓名" align="center" prop="realname" />
        <el-table-column v-if="hasData('phone')" label="手机号码" align="center" prop="phone" width="160" />
        <el-table-column v-if="hasData('parentId')" label="推荐人id" align="center" prop="parentId" width="180" />
        <el-table-column v-if="hasData('parentusername')" label="上级账号" align="center" prop="parentusername" width="120"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('userLevel')" label="会员等级" align="center" prop="userLevel" />
        <el-table-column v-if="hasData('status')" label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="stkj_number_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('addTime')" label="注册时间" align="center" prop="addTime" width="160" />
        <el-table-column v-if="hasData('addIp')" label="注册IP" align="center" prop="addIp" width="160"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('loginIp')" label="登录IP" align="center" prop="loginIp" width="160"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('mac')" label="MAC地址" align="center" prop="mac" width="160" />
        <el-table-column v-if="hasData('ip')" label="IP地址" align="center" prop="ip" width="160" />
        <el-table-column v-if="hasData('lastLoginTime')" label="最近登录时间" align="center" prop="lastLoginTime" width="200"
          :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['number:number:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['number:number:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改会员管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="numberFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="会员id" prop="id">
          <el-input v-model="form.id" placeholder="请输入会员id" clearable />
        </el-form-item>
        <el-form-item label="会员账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入会员账号" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="注册时间" prop="addTime">
          <el-date-picker clearable v-model="form.addTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择注册时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="注册IP" prop="addIp">
          <el-input v-model="form.addIp" placeholder="请输入注册IP" />
        </el-form-item>
        <el-form-item label="登录IP" prop="loginIp">
          <el-input v-model="form.loginIp" placeholder="请输入登录IP" />
        </el-form-item>
        <el-form-item label="MAC地址" prop="mac">
          <el-input v-model="form.mac" placeholder="请输入MAC地址" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="推荐人id" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入推荐人id" />
        </el-form-item>
        <el-form-item label="上级账号" prop="parentusername">
          <el-input v-model="form.parentusername" placeholder="请输入上级账号" />
        </el-form-item>
        <el-form-item label="会员等级" prop="userLevel">
          <el-input v-model="form.userLevel" placeholder="请输入会员等级" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in stkj_number_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最近登录时间" prop="lastLoginTime">
          <el-date-picker clearable v-model="form.lastLoginTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择最近登录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Number" lang="ts">
import { listNumber, getNumber, delNumber, addNumber, updateNumber, exportSelectedNumber,clearNumber } from '@/api/number/number';
import { NumberVO, NumberQuery, NumberForm } from '@/api/number/number/types';
import { globalHeaders } from '@/utils/request';
import { t } from 'vxe-table';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { stkj_number_status, sktj_sort_field, sktj_asc_desc } = toRefs<any>(proxy?.useDict('stkj_number_status', 'sktj_sort_field', 'sktj_asc_desc'));

const numberList = ref<NumberVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const numberFormRef = ref<ElFormInstance>();


/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/number/number/importData'
});
const uploadRef = ref<ElUploadInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: NumberForm = {
  id: undefined,
  username: undefined,
  realname: undefined,
  phone: undefined,
  addTime: undefined,
  addIp: undefined,
  loginIp: undefined,
  mac: undefined,
  ip: undefined,
  parentId: undefined,
  parentusername: undefined,
  userLevel: undefined,
  status: undefined,
  lastLoginTime: undefined,
}
const data = reactive<PageData<NumberForm, NumberQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    username: undefined,
    realname: undefined,
    parentId: undefined,
    userLevel: undefined,
    status: undefined,
    sortField: undefined,
    ascOrDesc: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "会员id不能为空", trigger: "blur" }
    ],
  }
});


const { queryParams, form, rules } = toRefs(data);

/** 查询会员管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNumber(queryParams.value);
  numberList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  numberFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: NumberVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const isAddOperation = ref(false); // 新增标志位

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加会员管理";
  isAddOperation.value = true; // 设置新增标志位
};

/** 修改按钮操作 */
const handleUpdate = async (row?: NumberVO) => {
  reset();
  dialog.visible = true;
  dialog.title = "修改会员管理";
  if (row) {
    // 获取选中的会员数据
    const res = await getNumber(row.id);
    form.value = { ...res.data }; // 将获取到的数据填充到表单中
  } else {
    // 如果没有传递 row 参数，则获取选中的单个会员数据
    if (ids.value.length === 1) {
      const res = await getNumber(ids.value[0]);
      form.value = { ...res.data }; // 将获取到的数据填充到表单中
    } else {
      form.value.id = ''; // 使用空字符串作为默认值
    }
  }
  isAddOperation.value = false; // 设置修改标志位
};



/** 提交按钮 */
const submitForm = () => {
  numberFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (isAddOperation.value) {
        // 如果是新增操作
        await addNumber(form.value).finally(() => buttonLoading.value = false);
      } else {
        // 如果是修改操作
        await updateNumber(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: NumberVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除会员管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delNumber(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户导入';
  upload.open = true;
};
/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('number/number/importTemplate', {}, `number_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('number/number/export', {
    ...queryParams.value
  }, `number_${new Date().getTime()}.xlsx`)
}

/** 导出选中按钮操作 */
const handleExportByIds = async (row?: NumberVO) => {
  try {
    const _ids = Array.isArray(row?.id) ? row?.id : Array.isArray(ids.value) ? ids.value : [];
    // 确保有数据被选中
    if (_ids.length === 0) {
      ElMessage.warning('请至少选择一项进行导出');
      return;
    }

    // 调用后端API进行导出操作，直接处理返回的Blob对象
    const response = await exportSelectedNumber(_ids);

    // 由于后端直接返回了Blob，我们可以直接处理这个Blob来下载文件
    //const url = window.URL.createObjectURL(new Blob([response]));
    const url = window.URL.createObjectURL(response as unknown as Blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `number_${new Date().getTime()}.xlsx`); // 自定义文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出选中数据时发生错误:', error);
    ElMessage.error('导出过程中发生错误，请检查网络或联系管理员');
  }
};

/**检查列中是否有数据，如果没有则隐藏该列 */
const checkColumn = (row: NumberVO, column: any) => {
  return row[column.property] ? true : false;
}
const hasData = (prop: string) => {
  // 检查中的至少一条数据是否包含prop属性且该属性有值
  return numberList.value.some(item => item[prop] && item[prop] !== '');
};


/**清空表数据 */
const handleDeleteAll = async () => {
  try {
      // 确认操作
      await proxy?.$modal.confirm('确定要清空表数据吗');
      // 开始清理并加载列表
      loading.value = true;
      await clearNumber();
      proxy?.$modal.msgSuccess("清空数据成功");
      getList();
    } catch (error) {
      // 捕获到错误时，关闭加载状态并给出错误提示
      loading.value = false;
      console.error("操作失败", error);
      //ElMessage.error("操作失败，请稍后重试");
    } finally {
      // 确保loading状态被正确关闭
      loading.value = false;
    }
}

onMounted(() => {
  getList();
});


</script>
